package com.hiyee.api.interceptors;

import com.hiyee.enums.UserStatus;
import com.hiyee.exception.GraceException;
import com.hiyee.grace.result.ResponseStatusEnum;
import com.hiyee.pojo.AppUser;
import com.hiyee.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户激活状态拦截器
 *
 * @author WangBin
 */
public class UserActiveInterceptor extends BaseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 未激活状体需提示激活才能继续操作
        String userId = request.getHeader("headerUserId");
        String userJson = redisOperator.get(REDIS_KEY_USER_INFO + userId);
        AppUser user = null;
        if(StringUtils.isNoneBlank(userJson)) {
            user = JsonUtils.jsonToPojo(userJson, AppUser.class);
        } else {
            GraceException.display(ResponseStatusEnum.AUTH_FORBIDDEN);
            return false;
        }
        if(user.getActiveStatus() == null || user.getActiveStatus() != UserStatus.ACTIVE.getValue()) {
            GraceException.display(ResponseStatusEnum.USER_NEED_ACTIVE);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
